//
//  MusicYue_V_ViewController.m
//  STL_ Animation
//
//  Created by 孙健 on 16/3/31.
//  Copyright © 2016年 STL. All rights reserved.
//
#import "STL.h"
#import "MusicYue_V_ViewController.h"
#import "ChannelPageMV_ViewController.h"
#import "MusicYue_V_TableViewCell.h"
#import "UIScrollView+MJRefresh.h"
#import "MusicYue_V_Model.h"
#import "STLPopup_window.h"
#import "LoadViewModel.h"
#import "LoadViewController.h"
#import "CoreDataManager.h"
#import "MvLoad.h"

#import "MVCollection.h"

#import "STLLoadMv.h"


@interface MusicYue_V_ViewController ()<UITableViewDataSource,UITableViewDelegate,STLPopup_windowDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *dataSourcetwo;
@property (nonatomic, strong) NSString *stringUrl;
@property (nonatomic, strong) UIView *viewTitle;
@property (nonatomic, strong) UIImageView *imageViewtITLE;
@property (nonatomic, strong) UILabel *labelTitle;
@property (nonatomic, strong) UILabel *labelMost;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, assign) BOOL isFrame;
@property (nonatomic, assign) BOOL isgoing;
@property (nonatomic, assign) NSInteger countAmount;
@property (nonatomic, strong) CoreDataManager *coredataManeger;
@property (nonatomic, strong) NSMutableArray *mvCollectArr;

@end

@implementation MusicYue_V_ViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.coredataManeger = [CoreDataManager shareCoreDataManager];
    NSLog(@"路径%@", self.coredataManeger.applicationDocumentsDirectory);
    [self loadMVCollect];
    self.view.backgroundColor = [UIColor blackColor];
       self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"prev"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(returnChannelVc)];
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    self.dataSourcetwo = [NSMutableArray arrayWithCapacity:0];
    NSLog(@"yici liangci");
    [self getdata];
    [self createTableView];
    //[self selectData];
   
}


- (void)returnChannelVc {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - 网络请求
- (void)getdata {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if ([self.type isEqualToString:@"program"]) {
        
        self.stringUrl = [NSString stringWithFormat:@"http://mapi.yinyuetai.com/program/videos.json?D-A=0&detail=true&offset=%ld&programId=%@&size=10",self.count,self.idName];
    } else {
        
        self.stringUrl = [NSString stringWithFormat:@"http://mapi.yinyuetai.com/channel/videos.json?D-A=0&channelId=%@&detail=true&offset=%ld&order=VideoPubDate&size=10",self.idName,self.count];
    }
    [SJAFNetTool GEtNetWithUrl:self.stringUrl WithBody:nil headerFile:Dictionary response:SJJSON success:^(id result) {
       
        
        if (result) {
            
            
            
            //获取tableview的头视图中的数据
            if (result[@"program"]) {
                NSDictionary *dic = result[@"program"];
                [self.imageViewtITLE sd_setImageWithURL:[NSURL URLWithString:dic[@"headImg"]]];
                self.labelTitle.text = dic[@"remark"];
                self.labelMost.text = dic[@"content"];
                }
            
            if (self.isFrame == YES) {
                [self.dataSource removeAllObjects];
                }
            
    if (result[@"channel"]) {
              
                NSDictionary *dic = result[@"channel"];
               
                NSNumber *boolNumber = dic[@"filter"];
    if ([boolNumber boolValue]) {
                    
                    [self createSegment];
                    self.isgoing = YES;
                    
            }
    else {
                   
                    self.isgoing = NO;
                   
        }

            }
            
            NSArray *array = result[@"videos"];
            for (NSDictionary *dic in array) {
                
                MusicYue_V_Model *musicModel = [[MusicYue_V_Model alloc] initWithDataSource:dic];
                [self.dataSource addObject:musicModel];
            }
           
            
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
        
        
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
        
}];
}

#pragma mark - 创建segment 
- (void)createSegment {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:view];
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"最新上传",@"最多播放"]];
    seg.tintColor = [UIColor blackColor];
    seg.backgroundColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    seg.selectedSegmentIndex = 1;
    seg.frame = CGRectMake(10, 0, view.bounds.size.width - 20, view.bounds.size.height);
    [seg addTarget:seg action:@selector(segchoose:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:seg];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"sanxian"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightButton)];
    
}

#pragma mark - 右侧导航栏点击按键事件
- (void)rightButton {
    
}


#pragma mark - seg点击事件
- (void)segchoose:(UISegmentedControl *)seg {
    
    
}



#pragma mark - 创建tableview
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero  style:UITableViewStylePlain];
    if (self.isgoing == YES) {
        
        self.tableView.frame = CGRectMake(0, 30, self.view.bounds.size.width, self.view.bounds.size.height - 100);
        
    }else {
        self.tableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64);
    }

    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[MusicYue_V_TableViewCell class] forCellReuseIdentifier:@"MusicYue_V_TableViewCell"];
    if ([self.type isEqualToString:@"program"]) {
        self.tableView.tableHeaderView = [self createHeadView];
    }
    
    [self.tableView setMj_header:[MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(shuaxinData)]];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshdata)];
    [self.view addSubview:self.tableView];
}

#pragma mark - 下拉刷新
- (void)shuaxinData {
    
    self.count = 0;
    self.isFrame = YES;
    [self getdata];
    [self.tableView.mj_header endRefreshing];
}

#pragma mark - 上拉刷新
- (void)refreshdata {
    self.isFrame = NO;
    self.count += 10;
    [self getdata];
    [self.tableView.mj_footer endRefreshing];
}


#pragma mark ----------- tableview的协议方法
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

#pragma mark ----------- tableview的协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MusicYue_V_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicYue_V_TableViewCell"];
    MusicYue_V_Model *mosicModel = self.dataSource[indexPath.row];
    
    cell.musicModel = mosicModel;
    cell.count = indexPath.row;
    cell.block = ^(NSInteger count){
    
        NSLog(@"%ld", count); 
        MusicYue_V_ViewController *musicVc = self; 
        STLPopup_window *window = [[STLPopup_window alloc] initWithFrame:musicVc.view.bounds with:@[@"下载",@"分享",@"收藏"]];
        window.delegate = musicVc;
        [musicVc.view addSubview:window];
        musicVc.countAmount = count;
    };
    
    return cell;
}

#pragma mark --------- 点击下载、收藏的view
- (void)chooseCount:(NSInteger)count WithTitle:(NSString *)title {
    
    if (count == 0 || [title isEqualToString:@"下载"]) {
        
    MusicYue_V_Model *musicModel = self.dataSource[self.countAmount];
        NSLog(@"%@", musicModel.title);
        
    STLZhuangTai stl = [self.coredataManeger selectData:musicModel.uhdUrl WithName:@"MvLoad"];
        
    NSLog(@"%ld", stl);
        
    if (stl == STLHave) {
            
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"您已经下载过此MV" preferredStyle:  UIAlertControllerStyleAlert];
            
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                
        }]];
            //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
            
 
    }else {
            
    MvLoad *mvload = [NSEntityDescription insertNewObjectForEntityForName:@"MvLoad" inManagedObjectContext:self.coredataManeger.managedObjectContext];
            
    mvload.url = musicModel.uhdUrl;
    mvload.title = musicModel.title;
    mvload.picture = musicModel.posterPic;
            
    [self.coredataManeger saveContext];
        
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"已添加至下载队列" preferredStyle:  UIAlertControllerStyleAlert];
            
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self startload:musicModel.uhdUrl];
        
        [self.coredataManeger saveContext];
    }]];
            //弹出提示框；
    [self presentViewController:alert animated:true completion:nil];
      }
    
    } else if (count == 2) {
        NSLog(@"~~~~~~!");
        MusicYue_V_Model *musicModel = self.dataSource[self.countAmount];
        BOOL isHave = NO;
        for (MVCollection *mvCollect in self.mvCollectArr) {
            
            if ([mvCollect.idName isEqualToString:musicModel.idName.stringValue]) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"该MV已收藏" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:sureAction];
                [self presentViewController:alertController animated:YES completion:nil];
                isHave = YES;
            }
        }
        
        if (isHave == NO) {
            MVCollection *mvCollect = [NSEntityDescription insertNewObjectForEntityForName:@"MVCollection" inManagedObjectContext:self.coredataManeger.managedObjectContext];
            mvCollect.idName = musicModel.idName.stringValue;
            mvCollect.hdUrl = musicModel.uhdUrl;
            mvCollect.artistName = musicModel.artistName;
            mvCollect.posterPic = musicModel.posterPic;
            mvCollect.title = musicModel.title;
            mvCollect.totalViews = musicModel.totalViews;
            mvCollect.albumImage = musicModel.albumImg;
            
            [self.coredataManeger saveContext];
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:sureAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        [self loadMVCollect];
    }

}

#pragma mark -------------开始下载
- (void)startload:(NSString *)url{
    
    [[STLLoadMv sharedInstance]download:url progress:^(CGFloat progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
        
    } state:^(DownloadState state) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            
        });

    }];
}

#pragma mark ---------创建头视图 有的有 有的没有
- (UIView *)createHeadView {
    
    self.viewTitle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width/2)];
    self.imageViewtITLE = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.viewTitle.bounds.size.width/2 - 20, self.viewTitle.bounds.size.height)];
    self.labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(self.viewTitle.bounds.size.width/2 - 10, 20, self.viewTitle.bounds.size.width - self.viewTitle.bounds.size.width/2 + 10, self.viewTitle.bounds.size.height/7)];
    self.labelMost = [[UILabel alloc] initWithFrame:CGRectMake(self.viewTitle.bounds.size.width/2 - 10, 45, self.viewTitle.bounds.size.width - self.viewTitle.bounds.size.width/2 + 10, self.viewTitle.bounds.size.height/7 * 3)];
    
    self.labelTitle.font = [UIFont systemFontOfSize:12];
    self.labelMost.font = [UIFont systemFontOfSize:12];
    self.labelMost.numberOfLines = 4;
    
    self.labelTitle.textColor = [UIColor grayColor];
    self.labelMost.textColor = [UIColor blackColor];
    
    
    
    [self.viewTitle addSubview:self.imageViewtITLE];
    [self.viewTitle addSubview:self.labelTitle];
    [self.viewTitle addSubview:self.labelMost];
    
    return self.viewTitle;
}

#pragma mark ----------- tableview的协议方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.view.bounds.size.width/4;
}


#pragma mark ----------- tableview的协议方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChannelPageMV_ViewController *channelPageVc = [[ChannelPageMV_ViewController alloc] init];
    MusicYue_V_Model *mosicModel = self.dataSource[indexPath.row];
    NSLog(@"%ld",indexPath.row);
    channelPageVc.idName = mosicModel.idName.stringValue;
    channelPageVc.title = mosicModel.title;
    channelPageVc.url = mosicModel.url;
    channelPageVc.urlOne = mosicModel.hdUrl;
    channelPageVc.urltwo = mosicModel.uhdUrl;
    channelPageVc.urlthree = mosicModel.shdUrl;
    channelPageVc.imageViewUrl = mosicModel.albumImg;
    [self.navigationController pushViewController:channelPageVc animated:YES];
}

#pragma mark - loadMVCollect 
- (void)loadMVCollect {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MVCollection" inManagedObjectContext:self.coredataManeger.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coredataManeger.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
    } else {
        self.mvCollectArr = [NSMutableArray arrayWithArray:fetchedObjects];
    }
}

//#pragma mark - insertMVCollect
//- (void)insertMVCollect {
//    
//}
@end
